import axios from 'axios';

const request = axios.create({
  // baseURL: 'http://localhost:8080',
  timeout: 30000,
  headers: { 'Content-Type': 'application/json' },
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 在请求发送之前请求头处理
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    config.headers['Access-Control-Allow-Origin'] = '*';
    config.headers['Access-Control-Allow-Methods'] = 'PUT, POST, GET, DELETE';
    config.headers['Access-Control-Allow-Private-Network'] = true;
    return config;
  },
  (error) => Promise.reject(error),
);

// 响应拦截器
request.interceptors.response.use(
  (response) => response.data,
  (error) => Promise.reject(error),
);

export default request;

export function queryJson(query: Object) {
  let key: keyof Object;
  let str = '?';
  for (key in query) {
    str += `${key}=${query[key]}&`;
  }
  return str.substring(0, str.length - 1);
}
